import JSZip from 'jszip'
/**
 * Check if an element has a class
 * @param {HTMLElement} ele
 * @param {string} cls
 * @returns {boolean}
 */
export function hasClass(ele: HTMLElement, cls: string) {
  return !!ele.className.match(new RegExp("(\\s|^)" + cls + "(\\s|$)"));
}

/**
 * Add class to element
 * @param {HTMLElement} ele
 * @param {string} cls
 */
export function addClass(ele: HTMLElement, cls: string) {
  if (!hasClass(ele, cls)) ele.className += " " + cls;
}

/**
 * Remove class from element
 * @param {HTMLElement} ele
 * @param {string} cls
 */
export function removeClass(ele: HTMLElement, cls: string) {
  if (hasClass(ele, cls)) {
    const reg = new RegExp("(\\s|^)" + cls + "(\\s|$)");
    ele.className = ele.className.replace(reg, " ");
  }
}

/**
 * 判断是否是外部链接
 *
 * @param {string} path
 * @returns {Boolean}
 */
export function isExternal(path: string) {
  const isExternal = /^(https?:|http?:|mailto:|tel:)/.test(path);
  return isExternal;
}

export function formatDate(date: Date, config: Object = {
  year: "numeric",
  month: "short",
  day: "numeric",
  hour: "numeric",
  minute: "numeric",
  second: "numeric",
  hour12: false,
}) {
  let res = new Date(date)
    .toLocaleDateString(
      "zh-CN",
      config
    )

    res = res.replace(/年|月/g, "-")
    res = res.replace(/日/g, "");
    
    return res;
}

export function formatParams(params: any, isDeep: boolean = false) {
  if (!isDeep) {
    return Object.keys(params)
      .filter((key) => params[key] !== null && params[key] !== undefined && params[key] !== "")
      .reduce((acc: any, key) => {
        acc[key] = params[key];
        return acc;
      }, {});
  }

  const newObj = Object.keys(params).reduce((acc: { [key: string]: any }, key: string) => {
    acc[key] = formatParams(params[key], true);
    return acc;
  }, {});

  return Object.keys(newObj)
    .filter((key) => newObj[key] !== null && newObj[key] !== undefined && newObj[key] !== "")
    .reduce((acc: { [key: string]: any }, key: string) => {
      acc[key] = newObj[key];
      return acc;
    }, {});
}

export const copyText = (content: string | number) => {
  const input = document.createElement("input");
  input.value = content.toString();
  document.body.appendChild(input);
  input.select();
  document.execCommand("copy");
  document.body.removeChild(input);

  ElMessage.success("复制成功");
};


export function throttle<T extends (...args: any[]) => any>(
  fn: T, 
  delay: number = 3000
): T {
  let lastCallTime = 0;
  
  return function(this: any, ...args: Parameters<T>): ReturnType<T> | void {
    const now = Date.now();
    if (now - lastCallTime >= delay) {
      lastCallTime = now;
      return fn.apply(this, args);
    }
  } as T;
}


export function downloadZipFile(data: any, fileName: string) {
  try {
    
    // 如果是Blob数据，尝试解压
    data.arrayBuffer().then((arrayBuffer: ArrayBuffer) => {
      console.log(arrayBuffer, 'arrayBuffer');
      
      JSZip.loadAsync(arrayBuffer).then((zip) => {
        return zip.generateAsync({ type: "blob" });
      }).then((content) => {
        const link = document.createElement("a");
        link.href = URL.createObjectURL(content);
        link.download = decodeURIComponent(fileName);
        link.click();
        URL.revokeObjectURL(link.href);
        ElMessage({
          type: 'success',
          message: '导出成功',
        });
      }).catch((error) => {
        console.error('解压失败:', error);
        // 如果解压失败，直接下载原文件
        const link = document.createElement("a");
        link.href = URL.createObjectURL(data);
        link.download = decodeURIComponent(fileName);
        link.click();
        URL.revokeObjectURL(link.href);
        ElMessage({
          type: 'success',
          message: '导出成功',
        });
      });
    });
  } catch (error) {
    console.error('下载文件失败:', error);
    ElMessage({
      type: 'error',
      message: '下载文件出现错误，请联系管理员！',
    });
  }
}
